#!/usr/local/bin/python3

#import sys
import SocketServer
#import socket
#import string
#import Queue
import threading
#import thread
#import time
#sys.path.insert(0, '/usr/share/pyshared/daemon')
#import daemon
import logger
import dlmhelpers

class MyUDPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        try:
            senderSocket = self.request[1]
            senderAddress = self.client_address
            command = bytes.decode(self.request[0]).strip()
            msg = Message.NewMessage(command, (senderSocket, senderAddress))

            if _debug_:
                print("\n")
                print("UDP RX: msg from {c}: {m}".format(c = msg.Sender[1], m = command))

            clearUDPPool()

            if msg is not None:
                if msg.IsCmd and msg.Name == 'XXX':
                    msg.Reply = "<{0}:???>".format(msg.Target)
                else:
                    inMsgPool.put(msg)
                    msg = udpMsgPool.get(True, 5)
            else:
                return

            if _debug_:
                print("UDP TX: msg to {c}: {m}".format(c = msg.Sender[1], m = msg.Reply))
                print("\n")
            msg.Sender[0].sendto(str.encode(msg.Reply), msg.Sender[1])
        except Exception as ex:
            if _debug_:
                print("UDP exception", ex)
            else:
                pass
